﻿using Common.Contract;
using Common.Contract.Customer;
using Common.Contract.Customer.Record;
using Common.Contract.Customer.Request.ReduceFee;
using Common.Contract.Customer.Response.ReduceFee;
using Common.Service;
using Common.Service.DataTables;
using Microsoft.Web.Mvc;
using SMECustomerWebsite.Core.Configuration;
using SMECustomerWebsite.Filters;
using SMECustomerWebsite.Models.Interface;
using SMECustomerWebsite.Models.ViewModels.ReduceRateFee;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;

namespace SMECustomerWebsite.Controllers
{
    public class ReduceRateFeeController : ControllerBase
    {
        [Authorize]
        [CustomActionFilter]
        public ActionResult Index()
        {
            return View();
        }
        [Authorize]
        [CustomActionFilter]
        public ActionResult AddNew(string cif)
        {
            CustomerReduceFeeInfoRecord resultCustomer = new CustomerReduceFeeInfoRecord();
            CustomerInfoViewModel vm = new CustomerInfoViewModel();
            vm.CurrentUser = CurrentUserRecord;
            if (!string.IsNullOrEmpty(cif))
            {
                resultCustomer = GetCustInfoByCif(cif);
            }

            vm.Customer = resultCustomer;
            var wizard = new StepInputReduceRequestViewModel();
            wizard.Initialize();
            wizard.Cif = cif;
            vm.InputStep = wizard;
            return View(vm);
        }

        [Authorize]
        [HttpPost]
        public ActionResult AddNew([Deserialize] StepInputReduceRequestViewModel wizard, IStepViewModel step)
        {
            wizard.Steps[wizard.CurrentStepIndex] = step;
            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(Request["next"]))
                {
                    wizard.CurrentStepIndex++;
                }
                else if (!string.IsNullOrEmpty(Request["prev"]))
                {
                    wizard.CurrentStepIndex--;
                }
                else
                {
                    // TODO: we have finished: all the step partial
                    // view models have passed validation => map them
                    // back to the domain model and do some processing with
                    // the results
                    return RedirectToAction("Index", "ReduceRateFee");
                }
            }
            else if (!string.IsNullOrEmpty(Request["prev"]))
            {
                // Even if validation failed we allow the user to
                // navigate to previous steps
                wizard.CurrentStepIndex--;
            }
            CustomerReduceFeeInfoRecord resultCustomer = new CustomerReduceFeeInfoRecord();
            CustomerInfoViewModel vm = new CustomerInfoViewModel();
            vm.CurrentUser = CurrentUserRecord;
            if (!string.IsNullOrEmpty(wizard.Cif))
            {
                resultCustomer = GetCustInfoByCif(wizard.Cif);
            }
            vm.Customer = resultCustomer;
            vm.InputStep = wizard;
            return View(vm);
        }

        #region Partial view
        [ChildActionOnly]
        [Authorize]
        public ActionResult ReduceFinanceInfo(string cif)
        {
            return PartialView();
        }
        [ChildActionOnly]
        [Authorize]
        public ActionResult ReduceBadbankInfo(string cif)
        {
            return PartialView();
        }
        [ChildActionOnly]
        [Authorize]
        public ActionResult ReduceLimitInfo(string cif)
        {
            return PartialView();
        }
        #endregion

        #region Helper method
        [Authorize]
        [HttpPost]
        public ActionResult ReduceFinanceInfoData(DataTablesPageRequest pageRequest, string cif)
        {
            DataTableResponse pageResponse = null;
            List<CustomerFinanceInfoRecord> resultCustomer = new List<CustomerFinanceInfoRecord>();
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                RetrieveCustomerFinanceInfoByCifRequest request = new RetrieveCustomerFinanceInfoByCifRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.ReduceRateFee.ReduceFinanceInfoData"
                    },
                    CurrentUser = CurrentUserRecord,
                    Lang = CurrentLang,
                    Cif = cif
                };
                var customerRecords = new RetrieveCustomerFinanceInfoByCifResponse();
                customerRecords = serviceClient.Proxy.RetrieveCustomerFinanceInfoByCif(request);
                resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<CustomerFinanceInfoRecord>() : customerRecords.Records;
                if (resultCustomer != null && resultCustomer.Count > 0)
                {
                    pageResponse = new DataTableResponse
                    {
                        sEcho = pageRequest.Echo,
                        iTotalRecords = customerRecords.Page.TotalRecords,
                        sColumns = pageRequest.ColumnNames,
                        aaData = resultCustomer.Select(x => new object[]{
                                                             x.Content,
                                                             x.N2,
                                                             x.N1,
                                                             x.N,
                                                             x.Note,
                                                           }).ToList()
                    };
                }
            }
            return Json(pageResponse);
        }

        [Authorize]
        [HttpPost]
        public ActionResult ReduceLimitInfoData(DataTablesPageRequest pageRequest, string cif)
        {
            DataTableResponse pageResponse = null;
            List<CustomerLimitInfoRecord> resultCustomer = new List<CustomerLimitInfoRecord>();
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                RetrieveCustomerLimitInfoByCifRequest request = new RetrieveCustomerLimitInfoByCifRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.ReduceRateFee.ReduceFinanceInfoData"
                    },
                    CurrentUser = CurrentUserRecord,
                    Lang = CurrentLang,
                    Cif = cif
                };
                var customerRecords = new RetrieveCustomerLimitInfoByCifResponse();
                customerRecords = serviceClient.Proxy.RetrieveCustomerLimitInfoByCif(request);
                resultCustomer = (customerRecords == null || customerRecords.Records == null) ? new List<CustomerLimitInfoRecord>() : customerRecords.Records;
                if (resultCustomer != null && resultCustomer.Count > 0)
                {
                    pageResponse = new DataTableResponse
                    {
                        sEcho = pageRequest.Echo,
                        iTotalRecords = customerRecords.Page.TotalRecords,
                        sColumns = pageRequest.ColumnNames,
                        aaData = resultCustomer.Select(x => new object[]{
                                                             x.GroupTypeLimit,
                                                             x.TypeLimit,
                                                             x.OnlineLimitQd.ToString("#,###", CultureInfo.GetCultureInfo("vi-VN").NumberFormat),
                                                             (x.TotalOsQd * -1).ToString("#,###", CultureInfo.GetCultureInfo("vi-VN").NumberFormat),
                                                             string.Empty
                                                           }).ToList()
                    };
                    pageResponse.aaData.Add(new object[]{
                        string.Empty,
                        string.Format("Tổng HMTD (A+B)"),resultCustomer.Where(x=>x.TypeLimit.Contains("Tổng")).Sum(x=>x.OnlineLimitQd), 
                        string.Empty, 
                        string.Empty, 
                        string.Empty
                    });
                }
            }
            return Json(pageResponse);
        }

        [Authorize]
        private CustomerReduceFeeInfoRecord GetCustInfoByCif(string cif)
        {
            CustomerReduceFeeInfoRecord resultCustomer = new CustomerReduceFeeInfoRecord();
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                RetrieveCustomerReduceInfoRequest request = new RetrieveCustomerReduceInfoRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "SMEsCustomer360Degree.Controllers.ReduceRateFee.GetCustInfoByCif"
                    },
                    CurrentUser = CurrentUserRecord,
                    Lang = CurrentLang,
                    Cif = cif
                };
                var customerRecords = new RetrieveCustomerReduceInfoResponse();
                customerRecords = serviceClient.Proxy.RetrieveCustomerReduceInfoByCif(request);
                resultCustomer = (customerRecords == null || customerRecords.Record == null) ? new CustomerReduceFeeInfoRecord() : customerRecords.Record;
            }
            return resultCustomer;
        }
        #endregion
    }
}